<template>
  <!-- <scroll-view
		  type="nested"
		  scroll-y
			class="top"
		>
		</scroll-view> -->
  <view class="header-view">
    <view class="step-count">
      <!-- <view class="go">GO</view> -->
      <!-- detailInfo.todaySteps -->
      <view>{{ options.activityStatus ? detailInfo.todaySteps : stepCount }}</view>
      <view class="go">今日步数</view>
      <!--  -->
      <view class="walk-img" @click="getSteps">
        <up-image src="https://jqgh-public.yqfoodec.com/20250405/%E7%BB%84%205@2x_55113.png" width="120rpx" height="120rpx"></up-image>
      </view>
    </view>

    <view class="header-btn" @click="handleActivityRules">
      <view class="text">活动规则</view>
      <up-icon name="arrow-right" color="#ffffff" size="14"></up-icon>
    </view>
    <view class="header-btn my-card" @click="handleMyCard">
      <view class="text">我的证书</view>
      <up-icon name="arrow-right" color="#ffffff" size="14"></up-icon>
    </view>
  </view>

  <view class="container">
    <view class="content">
      <view class="step-card">
        <!-- 活动标题和时间 -->
        <!-- 	<view class="card-top">	
					<view class="info">
						<view class="info-left">
							<view class="text1">
								<text>{{detailInfo.activityTitle}} </text>
							</view>
							<view class="text2">
								<up-icon name="clock" color="#999"></up-icon>
								<view>{{detailInfo.activityStartTime}}-{{detailInfo.activityEndTime}}</view>
							</view>
							<view class="text2">{{remainingTime}}</view>
						</view>
					</view>
					
				</view> -->

        <view class="card-bottom">
          <up-row gutter="5">
            <up-col span="4">
              <view class="op-item">
                <view style="display: flex; align-items: center">
                  <up-image src="/static/images/icon/activity/walking/001.png" width="28rpx" height="38rpx"></up-image>
                  <view class="op-name">目标步数</view>
                </view>
                <view class="op-value">{{ detailInfo.dailyCapping }}</view>
              </view>
            </up-col>
            <up-col span="4">
              <view class="op-item middle-view">
                <view style="display: flex; align-items: center">
                  <up-image src="/static/images/icon/activity/walking/002.png" width="28rpx" height="38rpx"></up-image>
                  <view class="op-name">行走里程</view>
                </view>
                <view class="op-value">{{ detailInfo.todayKilometres }}</view>
              </view>
            </up-col>
            <up-col span="4">
              <view class="op-item">
                <view style="display: flex; align-items: center">
                  <up-image src="/static/images/icon/activity/walking/003.png" width="28rpx" height="38rpx"></up-image>
                  <view class="op-name">消耗卡路里</view>
                </view>
                <view class="op-value">{{ detailInfo.todayCumulativeCaloriesBurned }}</view>
              </view>
            </up-col>
          </up-row>
        </view>

        <up-gap height="15"></up-gap>
        <up-image :src="detailInfo.activityBanner || bg" width="100%" height="118" radius="10" mode="widthFix"></up-image>
        <up-gap height="15"></up-gap>
        <!-- functionPanel: [4, 1] -->
        <!-- 
					1. 已结束就不显示箭头了，每个都显示已结束
					2. 已结束  知识问答没法看，不知道显示哪一天的，其他都可以进去看 
				-->
        <view class="op-list">
          <view v-for="(dict, index) in functionPanelList" :key="index" class="op-item" @click="handleRedirect(dict.url)">
            <view>
              <up-image v-if="dict.dictValue == '0'" src="https://jqgh-public.yqfoodec.com/20250405/%E7%9F%A9%E5%BD%A2%2017@2x_54442.png" width="50rpx" height="50rpx" shape="circle"></up-image>
              <up-image v-else src="https://jqgh-public.yqfoodec.com/20250405/11_54426.png" width="50rpx" height="50rpx" shape="circle"></up-image>
            </view>
            <view class="op-name">{{ dict.dictLabel }}</view>
            <up-image v-if="options.activityStatus" src="https://jqgh-public.yqfoodec.com/20250417/over_56994.png" width="60rpx" height="60rpx" shape="circle"></up-image>
            <view v-else class="right-view">
              <up-icon name="arrow-right" size="12" color="#FF0808"></up-icon>
            </view>
          </view>
          <view v-for="(dict, index) in detailInfo.activityBriskWalkFeatureList" :key="index" class="op-item" @click="handleCustomPanel(dict)">
            <view v-if="dict.businessIcon">
              <up-image :src="dict.businessIcon" width="50rpx" height="50rpx" shape="circle"></up-image>
            </view>
            <view v-else>
              <!-- businessType: 2,知识竞赛， 4 随手拍 -->
              <up-image v-if="dict.businessType == 2" src="https://jqgh-public.yqfoodec.com/20250405/%E7%9F%A9%E5%BD%A2%2016@2x_54464.png" width="50rpx" height="50rpx" shape="circle"></up-image>
              <up-image v-else src="https://jqgh-public.yqfoodec.com/20250405/%E7%9F%A9%E5%BD%A2%2011@2x_54453.png" width="50rpx" height="50rpx" shape="circle"></up-image>
            </view>
            <view class="op-name" style="display: flex; align-items: center">
              <view style="margin-right: 20rpx">{{ dict.businessName }}</view>
              <!-- 已完成盖章 -->
              <template v-if="Number(options.id) < 35">
                <up-image
                  v-if="dict.businessType == 2 && dict.whetherRandom == 1 && dict.todayComplete"
                  src="https://jqgh-public.yqfoodec.com/20250416/wanc_33547.png"
                  width="60rpx"
                  height="60rpx"
                  shape="circle"
                ></up-image>
                <up-image
                  v-if="dict.businessType == 4 && dict.whetherRandom == 1 && dict.todayComplete"
                  src="https://jqgh-public.yqfoodec.com/20250416/wanc_33547.png"
                  width="60rpx"
                  height="60rpx"
                  shape="circle"
                ></up-image>
              </template>
            </view>
            <!-- 已结束盖章 -->
            <template v-if="Number(options.id) < 35">
              <up-image v-if="options.activityStatus" src="https://jqgh-public.yqfoodec.com/20250417/over_56994.png" width="60rpx" height="60rpx" shape="circle"></up-image>
              <view v-else class="right-view">
                <up-icon name="arrow-right" size="12" color="#FF0808"></up-icon>
              </view>
            </template>
            <template v-else>
              <view class="right-view">
                <up-icon name="arrow-right" size="12" color="#FF0808"></up-icon>
              </view>
            </template>
          </view>
        </view>
      </view>
      <up-gap height="15"></up-gap>
      <!-- <view class="card-view">
				<view class="card-point">
					<view class="tilte">集卡片赢积分</view>
					<view class="subtitle">解锁站点即可获得卡片</view>
					<view class="card-list">
						<view class="card-item" :style="`width: ${cardWidth}px`" v-for="(item, index) in cardData.activityCardList" :key="index">
							<view v-if="cardData.selfCardList == null">
								<up-image :src="img" :width="`${cardWidth}px`" height="129px" radius="2"></up-image>
							</view>
							<view v-else>
								<view v-if="selfCardList.length > 0">
									<up-image :src="selfCardList.indexOf(item.cardName)!==-1?item.cardPicture:img" :width="`${cardWidth}px`" height="128px" radius="2"></up-image>
								</view>
								<view v-else>
									<up-image :src="img" :width="`${cardWidth}px`" height="129px" radius="2"></up-image>
								</view>
								
							</view>
							<view style="margin-top: 10rpx;">{{item.cardName}}</view>
						</view>
					</view>
					<up-empty mode="data" text="暂无卡片" icon="https://jqgh-public.yqfoodec.com/20250405/%E7%BB%84%2016@2x_53897.png" v-if="!cardData.activityCardList"></up-empty>
					
				</view>
				<view class="card-point">
					<view class="rule-title">集卡规则说明</view>
					<view class="rule-explanation">
						解锁关卡后，会依次获得“劳模精神、劳动精神、工匠精神、首都工匠、大国工匠、喜迎华诞”证书直至完成全都路线。
					</view>
				</view>
			</view> -->

      <view class="ranking-list">
        <view class="user-info">
          <view class="avatar-view">
            <up-avatar :src="userInfo.avatar" size="50"></up-avatar>
          </view>
          <view>
            <view class="name">{{ userInfo.realName }}</view>
            <view>{{ userInfo.orgName }}</view>
          </view>
        </view>
        <up-gap height="30"></up-gap>
        <view class="user-rank-view">
          <view class="rank-item">
            <view>个人排行</view>
            <view class="value">{{ personalRank }}</view>
          </view>
          <view class="rank-item">
            <view>今日排行</view>
            <view class="value">{{ todayRank }}</view>
          </view>
          <view class="rank-item">
            <view>工会排行</view>
            <view class="value">{{ unionRank }}</view>
          </view>
        </view>
        <up-gap height="15"></up-gap>
        <view class="user-rank-view">
          <view class="rank-item">
            <view>活动人数</view>
            <view class="value">{{ detailInfo.participantsNumber }}</view>
          </view>
          <view class="rank-item">
            <view>累计步数</view>
            <view class="value">{{ detailInfo.selfCumulativeSteps }}</view>
          </view>
          <view class="rank-item">
            <view>累计公里</view>
            <view class="value">{{ detailInfo.selfKilometres }}</view>
          </view>
        </view>
      </view>
      <up-gap height="50"></up-gap>
      <up-modal :show="show" :content="`恭喜，达到阶梯积分奖励标准，获得${obtainedPoints}积分`" @confirm="show = false"></up-modal>
    </view>
  </view>
</template>

<script>
import { activityApi } from '@/api/activity/activity-app.js'
import config from '@/config'
import { getToken } from '@/utils/auth'
import myCard from './myCard.vue'

export default {
  components: {
    myCard,
  },
  data() {
    return {
      bg: 'https://jqgh-public.yqfoodec.com/20250411/bg-2_64874.jpg',
      detailInfo: {},
      remainingTime: '',
      options: {},
      rankingParams: {
        activityId: 0,
        todayFlag: false,
      },
      rankData: [],
      orgRankData: [],
      userInfo: {},
      userRank: {},
      orgRank: {},
      obtainedPoints: 0,
      checkboxList: [
        { dictLabel: '排行榜', dictValue: '0', url: 'ranking', pid: null },
        { dictLabel: '竞赛地图', dictValue: '1', url: 'map', pid: null },
      ],
      functionPanelList: [],
      personalRank: 0,
      todayRank: 0,
      unionRank: 0,
      diff: 0,
      show: false,
      stepCount: null,
      cardWidth: 0,
      selfCardList: [],
      cardData: {},
      img: 'https://jqgh-public.yqfoodec.com/20250408/card_73507.jpg',
    }
  },
  onLoad(options) {
    // activityStatus
    // joinFlag 是否已报名，获取步数之前需要先判断用户是否参与了该活动；随手拍、知识竞赛也是一样的道理
    this.userInfo = uni.getStorageSync('userInfo')

    this.options = options
    console.log(options)
    const id = options.id
    this.rankingParams.activityId = id
    uni.setNavigationBarTitle({
      title: options.title || '健步走',
    })

    this.getUserRankDetail()
    this.getUserRankDetail2()
    this.getOrgRankDetail()
    this.getsize()
  },

  onShow() {
    this.getDetail()
    this.getDataList()
  },
  methods: {
    getsize() {
      let that = this
      uni.getSystemInfo({
        success(res) {
          let width = res.windowWidth - 4 * 16
          that.cardWidth = width / 3 - 10
        },
      })
    },
    async getDataList() {
      const id = this.options.id
      const result = await activityApi.getMyCard(id)

      this.cardData = result.data
      if (result.data.selfCardList !== null) {
        let selfCardList = []
        result.data.selfCardList.forEach((item) => {
          selfCardList.push(item.cardName)
        })
        this.selfCardList = selfCardList
      }
    },
    async getDetail() {
      const result = await activityApi.getDetail(this.options.id)
      const array = []
      result.data.functionPanel.forEach((item) => {
        this.checkboxList.forEach((dict) => {
          if (item == Number(dict.dictValue)) {
            array.push(dict)
          }
        })
      })
      this.functionPanelList = array
      // detailInfo.functionPanel
      this.detailInfo = result.data
      this.remainingTime = this.calculateTimeRemaining(result.data.activityEndTime)

      // #ifdef H5
      const app = getApp()
      let userInfo = app.globalData.currentUser
      this.stepCount = userInfo.steps
      // #endif
    },
    async getUserRankDetail() {
      const rankData = await activityApi.userRanking(this.rankingParams)
      if (rankData.data.length > 0) {
        rankData.data.forEach((item) => {
          if (this.userInfo.memberId == item.id) {
            // 个人排行
            this.personalRank = item.ranks
          }
        })
      }
    },
    async getUserRankDetail2() {
      this.rankingParams.todayFlag = true
      const rankData = await activityApi.userRanking(this.rankingParams)
      if (rankData.data.length > 0) {
        rankData.data.forEach((item) => {
          if (this.userInfo.memberId == item.id) {
            // 今日排行
            this.todayRank = item.ranks
          }
        })
      }
    },
    async getOrgRankDetail() {
      const rankData = await activityApi.orgRanking(this.options.id)
      if (rankData.data.length > 0) {
        rankData.data.forEach((item) => {
          if (this.userInfo.orgId == item.orgId) {
            this.unionRank = item.ranks
          }
        })
      }
    },
    // 获取步数
    async getSteps() {
      console.log('点击')
      let that = this
      // 调用微信登录方法获取code
      uni.login({
        provider: 'weixin',
        success(res) {
          //console.log(res.code)
          //调用微信步数接口获取(encryptedData、iv)
          uni.getWeRunData({
            success(res2) {
              console.log(res2)
              //调用后端接口,传递参数
              uni.request({
                url: config.baseUrl + '/events/activity_brisk_walk/get/run/count',
                method: 'POST',
                header: {
                  Authorization: getToken(),
                },
                data: {
                  code: res.code,
                  encryptedData: res2.encryptedData,
                  iv: res2.iv,
                  briskWalkId: that.options.id,
                },
                success(res3) {
                  // console.log(res3)
                  that.stepCount = res3.data.data.stepCount
                  that.obtainedPoints = res3.data.data.obtainedPoints // 积分大于0要弹窗
                  if (res3.data.data.obtainedPoints > 0) {
                    that.show = true
                  }
                },
              })
            },
            fail: (e) => {
              console.log(e)
            },
          })
        },
      })
    },
    calculateTimeRemaining(endTime) {
      const endDate = new Date(endTime.replace(' ', 'T'))
      // 获取当前时间
      const now = new Date()

      // 计算时间差（毫秒）
      const diff = endDate - now

      // 如果活动已结束
      if (diff <= 0 || this.options.activityStatus) {
        // return "活动已结束";
        return false
      }

      this.diff = diff
      // 活动已经结束，不能获取步数和排名了，步数字段后台要加
      this.getSteps()

      // 计算天数、小时、分钟
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
      // console.log(`${days}天 ${hours}小时 ${minutes}分`)

      return `活动剩余${days}天 ${hours}小时 ${minutes}分`
    },
    handleRedirect(name) {
      uni.navigateTo({
        url: `/brisk-walking/${name}?id=${this.detailInfo.id}&activityBanner=${this.detailInfo.activityBanner}&siteBgImage=${this.detailInfo.siteBgImage}`,
      })
    },
    handleCustomPanel(item) {
      // businessType：知识竞赛 2，随手拍4
      if (item.businessType == 2) {
        // 已结束就不能看了，因为不知道查看哪天的
        if (this.diff <= 0 || this.options.activityStatus) {
          uni.showToast({
            title: '活动已经结束啦~',
            icon: 'error',
          })
          return false
        }
        // 知识竞赛 分为是否随机 whetherRandom
        // console.log(item.whetherRandom)
        if (item.whetherRandom == 1) {
          if (!item.todayComplete) {
            uni.navigateTo({
              url: `/brisk-walking/knowledgeContest?id=${item.businessId}&walkFeatureId=${item.id}&briskWalkId=${item.briskWalkId}&whetherRandom=${item.whetherRandom}`,
            })
          } else {
            // 每日答题详情
            // uni.navigateTo({
            // 	url: `/brisk-walking/knowledgeContest?id=${item.businessId}&walkFeatureId=${item.id}&detail=true`
            // });
            // 不让看了
            // uni.navigateTo({
            // 	url: `/brisk-walking/components/answer-details?walkFeatureId=${item.id}`
            // });
            uni.showToast({
              title: '今日的任务完成',
              icon: 'error',
            })
          }
        } else {
          if (!item.whetherComplete) {
            uni.navigateTo({
              url: `/brisk-walking/knowledgeContest?id=${item.businessId}&walkFeatureId=${item.id}&briskWalkId=${item.briskWalkId}&whetherRandom=${item.whetherRandom}`,
            })
          } else {
            uni.showToast({
              title: '今日的任务完成',
              icon: 'error',
            })
          }
        }
      } else {
        // 随手拍 任务完成可以查看，但是不能发布
        let isPublish = true
        if (item.whetherRandom == 1) {
          if (item.todayComplete) {
            isPublish = false
          }
        } else {
          if (item.whetherComplete) {
            isPublish = false
          }
        }
        // 活动结束了不能发布
        if (this.diff <= 0 || this.options.activityStatus) {
          isPublish = false
        }
        // console.log(isPublish) // 是否可以发布，完成任务了不能发布
        uni.navigateTo({
          url: `/brisk-walking/instashot/list?id=${this.detailInfo.id}&walkFeatureId=${item.id}&isPublish=${isPublish}&businessId=${item.businessId}`,
        })
      }
    },
    // 活动规则
    handleActivityRules() {
      uni.navigateTo({
        url: `/brisk-walking/activityRules?id=${this.options.id}&type=1`,
      })
    },
    // 我的卡片
    handleMyCard() {
      uni.navigateTo({
        url: `/brisk-walking/myCard?id=${this.options.id}`,
      })
    },
    onShareAppMessage() {
      return {
        title: this.options.title, //分享的标题
        path: `/brisk-walking/detail?title=${this.options.title}&id=${this.options.id}`, //点击分享链接之后进入的页面路径
        imageUrl: '', //分享发送的链接图片地址
        success() {
          // 分享完成，请注意此时不一定是成功分享
          uni.showToast({
            title: '分享成功',
            duration: 3500,
            icon: 'success',
          })
        },
        fail() {
          // 分享失败
          uni.showToast({
            title: '分享失败',
            duration: 3500,
            icon: 'error',
          })
        },
      }
    },
  },
}
</script>

<style lang="scss" scoped>
@import '@/uni.scss';

.top {
  height: 60vh;
}
.header-view {
  height: 420rpx;
  background-color: #d81e06;
  position: relative;
  display: flex;
  justify-content: center;
  padding-top: 40rpx;
  .step-count {
    border: 4px solid #fff;
    width: 292rpx;
    height: 292rpx;
    background-color: #d83030;
    color: #fff;
    border-radius: 292rpx;
    text-align: center;

    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: 56rpx;
    .go {
      font-size: 36rpx;
    }

    :deep(.u-iconfont) {
      color: #fff !important;
    }
    .walk-img {
      position: absolute;
      bottom: 30px;
    }
  }
  .header-btn {
    position: absolute;
    top: 30rpx;
    right: 0;
    width: 176rpx;
    height: 54rpx;
    font-weight: 500;
    text-align: center;
    line-height: 54rpx;
    background: rgba(0, 0, 0, 0.2);
    color: #ffffff;
    font-size: 28rpx;
    border-top-left-radius: 46rpx;
    border-bottom-left-radius: 46rpx;
    display: flex;
    justify-content: center;
    .text {
      margin-right: 10rpx;
    }
  }
  .my-card {
    top: 100rpx;
  }
}
.container {
  position: absolute;
  left: 0;
  right: 0;
  padding: 0 16px;
  background-color: #f5f6fa;
}
.content {
  .step-card {
    margin-top: -40px;
    font-size: 28rpx;
    color: $uni-text-color;
    // 活动标题
    .card-top {
      display: flex;
      flex-direction: column;
      align-items: center;
      .title {
        padding: 10rpx 0;
      }

      .info {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 36rpx;

        .text1 {
          font-weight: bold;
          padding: 5rpx 0;
        }

        .color2 {
          color: $uni-color-primary;
        }

        .text2 {
          display: flex;
          align-items: center;
          margin-top: 10rpx;
          font-size: 28rpx;
          color: $uni-text-color-grey;
        }
      }
    }
    .card-bottom {
      padding: 30rpx 0 50rpx 0;
      border-radius: 20rpx;
      background-color: #fff;
      .u-row {
        width: 100%;
      }
      display: flex;
      justify-content: space-around;
      align-items: center;
      .op-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        text-align: center;
        color: #8c8c8c;
        .op-name {
          font-size: 28rpx;
          margin-left: 6rpx;
          margin-right: 20rpx;
        }
        .op-value {
          font-size: 48rpx;
          padding-top: 10rpx;
          line-height: 32rpx;
          margin-top: 20rpx;
        }
      }
      .middle-view {
        border-left: 1px solid #eee;
        border-right: 1px solid #eee;
      }
    }
  }

  .op-list {
    padding: 30rpx;
    border-radius: 20rpx;
    background-color: #fff;
    .op-item {
      display: flex;
      align-items: center;
      font-size: 30rpx;
      padding: 20rpx 0;
      border-bottom: 1px solid #eee;

      .op-name {
        flex: 1;
        padding-left: 20rpx;
      }
      .right-view {
        width: 40rpx;
        height: 40rpx;
        border-radius: 40rpx;
        background: rgba(231, 70, 64, 0.2);
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }

  .ranking-list {
    border-radius: 20rpx;
    padding: 30rpx;
    background-color: #d81e06;
    .user-info {
      display: flex;
      font-size: 28rpx;
      color: #fff;
      .avatar-view {
        border: 2px solid #fff;
        border-radius: 50%;
        margin-right: 20rpx;
        width: 50px;
        height: 50px;
      }
      .name {
        font-size: 36rpx;
        margin-bottom: 10rpx;
      }
    }
    .user-rank-view {
      color: #fff;
      font-size: 28rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .rank-item {
        text-align: center;
        line-height: 60rpx;
        .value {
          font-size: 36rpx;
        }
      }
    }
  }
}

.card-view {
  .card-point {
    background-color: #fff;
    border-radius: 20rpx;
    margin-bottom: 30rpx;
    padding: 16px;
    .tilte {
      font-size: 48rpx;
      color: #fc820a;
      text-align: center;
    }
    .subtitle {
      color: #8c8c8c;
      font-size: 28rpx;
      text-align: center;
    }
    .card-list {
      display: flex;
      flex-wrap: wrap;
      justify-content: flex-start;
      margin-top: 30rpx;
      .card-item {
        // flex: 1;
        text-align: center;
        font-size: 28rpx;
        // padding: 10rpx;
        margin: 0 5px 10px 5px;
      }
    }
    .card-list::after {
      height: 0;
      visibility: hidden;
    }
  }
  .rule-title {
    font-size: 32rpx;
  }
  .rule-explanation {
    color: #8c8c8c;
    font-size: 28rpx;
    margin: 20rpx 0;
  }
}
</style>
